// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
//  IOSCharArray.m
//  JreEmulation
//
//  Created by Tom Ball on 6/14/11.
//

#import "IOSCharArray.h"
#import "IOSPrimitiveClass.h"
//#import "java/lang/Character.h"

@implementation IOSCharArray

+ (id)arrayWithCharacters:(const unichar *)chars count:(NSUInteger)count {
  return [[[self alloc] initWithCharacters:chars
                                     count:count] j2objc_autorelease];
}

- (id)initWithCharacters:(const unichar *)chars count:(NSUInteger)count {
  if ((self = [self initWithLength:count])) {
    if (NULL != chars) {
      memcpy(self.storage.mutableBytes, chars, self.storage.length);
    }
  }
  return self;
}

- (unichar)charAtIndex:(NSUInteger)index {
  [self checkIndex:index];
  
  const unichar *buffer = (const unichar *)self.storage.bytes;
  return buffer[index];
}

- (unichar)replaceCharAtIndex:(NSUInteger)index withChar:(unichar)c {
  [self checkIndex:index];
  
  unichar *buffer = (unichar *)self.storage.mutableBytes;
  buffer[index] = c;
  return c;
}

- (unichar *)getChars {
  unichar *result = (unichar *)calloc(self.storage.length, 1);
  [self getChars:result length:self.count];
  return result;
}

- (void)getChars:(unichar *)buffer length:(NSUInteger)length {
  [self checkIndex:(length - 1)];
  memcpy(buffer, self.storage.bytes, length * [[self class] elementLength]);
}

- (unichar)incr:(NSUInteger)index {
  [self checkIndex:index];
  
  unichar *buffer = (unichar *)self.storage.mutableBytes;
  return ++buffer[index];
}

- (unichar)decr:(NSUInteger)index {
  [self checkIndex:index];
  
  unichar *buffer = (unichar *)self.storage.mutableBytes;
  return --buffer[index];
}

- (unichar)postIncr:(NSUInteger)index {
  [self checkIndex:index];
  
  unichar *buffer = (unichar *)self.storage.mutableBytes;
  return buffer[index]++;
}

- (unichar)postDecr:(NSUInteger)index {
  [self checkIndex:index];
  
  unichar *buffer = (unichar *)self.storage.mutableBytes;
  return buffer[index]--;
}

- (NSString *)descriptionOfElementAtIndex:(NSUInteger)index {
  return [NSString stringWithFormat:@"%C", [self charAtIndex:index]];
}

- (IOSClass *)elementType {
  return [[[IOSPrimitiveClass alloc] initWithName:@"char"
                                             type:@"C"] j2objc_autorelease];
}

+ (NSUInteger)elementLength
{
  return sizeof(unichar);
}

@end
